// pages/login/login.js
const app = getApp()

Page({
  data: {
    canIUseGetUserProfile: false,
    userInfo: null,
    hasUserInfo: false,
    locationInfo: null
  },

  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    this.checkLoginStatus()
  },

  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo')
    const locationInfo = wx.getStorageSync('locationInfo')
    
    if (userInfo) {
      app.globalData.userInfo = userInfo
      app.globalData.userLocation = locationInfo || {
        latitude: 0,
        longitude: 0,
        speed: 0,
        accuracy: 0
      }
      app.globalData.hasUserInfo = true
      
      wx.switchTab({
        url: '/pages/index/index'
      })
    }
  },

  getUserProfile() {
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        app.globalData.userInfo = res.userInfo
        app.globalData.hasUserInfo = true
        wx.setStorageSync('userInfo', res.userInfo)
        this.getUserLocation()
      },
      fail: (err) => {
        console.error('获取用户信息失败:', err)
        wx.showToast({
          title: '授权失败',
          icon: 'none'
        })
      }
    })
  },

  getUserLocation() {
    // 位置功能已禁用
    const locationInfo = {
      latitude: 0,
      longitude: 0,
      speed: 0,
      accuracy: 0
    }
    this.setData({
      locationInfo: locationInfo
    })
    app.globalData.userLocation = locationInfo
    wx.setStorageSync('locationInfo', locationInfo)
    this.getOpenId()
  },

  getOpenId() {
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        app.globalData.openid = res.result.openid
        this.saveUserInfoToCloud()
      },
      fail: err => {
        console.error('获取openid失败:', err)
      }
    })
  },

  saveUserInfoToCloud() {
    const db = wx.cloud.database()
    const { userInfo, locationInfo } = this.data
    
    db.collection('users').add({
      data: {
        openid: app.globalData.openid,
        userInfo: userInfo,
        location: locationInfo,
        createTime: db.serverDate(),
        lastLoginTime: db.serverDate()
      },
      success: () => {
        wx.switchTab({
          url: '/pages/index/index'
        })
      },
      fail: err => {
        console.error('保存用户信息失败:', err)
      }
    })
  }
})